﻿@{
    ViewBag.Title = "CodeView";
}

<h2>Posts: An explanation of Post code</h2>

<p>
    <strong>
        This is a summary of the main parts used to list, detail, create, edit and delete Post entries via a <abbr title="Data Transfer Object">DTO</abbr>
        This type of services that needs a <abbr title="Data Transfer Object">DTO</abbr> are used then the data class have dependent foreign keys that
        need to be manipulated before the data class can be written to the database.
    </strong>
</p>
<p>
    The headers contain links to the code on GitHub for you to look at.
    For most of you the links to the code will be sufficient, but more information is available by clicking on the panel titles.
</p>

<h3>The Posts Controller</h3>
<p>
    The <code>PostsController</code>
    (see here for <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/SampleWebApp/Controllers/PostsController.cs" target="_blank">code on GitHub</a>)
    uses the GenericService's <abbr title="Data Transfer Object">DTO</abbr> version of the database commands, which are injected into each action as a parameter.
    The PostsController has <code>List</code>, <code>Detail</code>, <code>Create</code>, <code>Update</code> and <code>Delete</code> actions on the Post data class.
</p>
<p>
    Click on the panel below to get more details about how this works.
</p>
<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a data-toggle="collapse" href="#PostsController">
                PostsController Database Actions
            </a>
        </h4>
        <div id="PostsController" class="panel-collapse collapse">
            <div class="panel-body">
                <dl>
                    <dt>Index Action - List of Posts</dt>
                    <dd>
                        <p>Let's look at the Index action in a detail because it has some standard patterns you will see on other actions.</p>
                        <p>
                            The Index action's job is to produce a list of posts, but using a <abbr title="Data Transfer Object">DTO</abbr>
                            to combine data from linked tables to produce a user-friendly display. In this case I have listed the code here as its really short:
                        </p>
                        <code>
                            public ActionResult Index(IListService service)<br />
                            {<br />
                            &nbsp;&nbsp;&nbsp;&nbsp;View(service.GetAll&lt;SimplePostDto&gt;().ToList());<br />
                            }<br />
                        </code>
                        <p>Things to note:</p>
                        <ul>
                            <li>
                                Notice that the service is injected by DI into the action as a parameter.
                                This is the standard way that all services are created in SampleMvcWebApp.
                                It is explained in more detail in <a href="#di-section">Dependency Injection</a> section.
                            </li>
                            <li>
                                This service has one command, <code>.GetAll&lt;T&gt;()</code>, which returns
                                <code>IQueryable&lt;T&gt;</code>, where T is either a class that is used in EF or
                                a DTO that has inherited from EfGenericDto or EfGenericDtoAsync.
                                In this case the <code>IQueryable</code> result is turned into a List to show in the view.
                            </li>
                        </ul>
                    </dd>
                    <dt>One stage actions List, Detail and Delete</dt>
                    <dd>
                        <p>
                            List, Detail and Delete have only have one stage as there is no setup needed.
                            <em>Detail and Delete do need a reference to the entry to act on, but that normally comes from a list entry or a link.</em>
                        </p>
                    </dd>
                    <dt>Two stage actions like Edit and Create</dt>
                    <dd>
                        <p>
                            Edit and Create are always a two stage action:
                        </p>
                        <ol>
                            <li>
                                The <code>xxxSetupService</code> is run to get the data to show in a Html Form ready for input or edit by the user.
                            </li>
                            <li>
                                When the form is Submitted then the main part of the service, either <code>UpdateService</code> or <code>CreateService</code>
                                takes that data and updates the data item.
                                <em>see more about this under <a href="#generic-services-section">Generic Services</a>, two stage services.</em>
                            </li>
                        </ol>

                    </dd>
                    <dt>Handling errors</dt>
                    <dd>
                        <p>
                            In robust applications you should check data as it moves deeping into the system so that
                            bad or bogus is not let through. MVC is the first validation but GenericServices, in
                            conjunction with <abbr title="Entity Framework">EF</abbr> carries out further checks.
                        </p>
                        <p>
                            In the Create and Edit Actions you will see checks happening at two stages:
                        </p>
                        <ol>
                            <li>
                                Checking that the data that came in from the HttpPost is correct. If it isn't it calls
                                <code>service.ResetDto(dto)</code> which makes sure that any lists used in the UI are refilled
                                before the dto is redisplayed with model errors
                            </li>
                            <li>
                                After the service has run if raised by the <abbr title="Entity Framework">EF</abbr> validation,
                                then they are returned in the status.
                                In the case of Create or Edit these are then copied into the ModelState of the dto before
                                it is redisplayed.
                                <em>
                                    Note that the service internally runs the <code>service.ResetDto(dto)</code>
                                    method if it finds an error so that the dto is ready to display.
                                </em>
                            </li>
                        </ol>
                        <em>
                            The SampleMvcWepApps DbContext purposely includes a test inside
                            <abbr title="Entity Framework">EF</abbr>'s <code>SaveChanges()</code> method to check that the
                            Tag property <code>Slug</code> is unique to show this in action. Also the <code>Post</code> class
                            (<a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/DataLayer/DataClasses/Concrete/Post.cs" target="_blank">code</a>)
                            is a <code>IValidatableObject</code> with some unusual valdation about sheep and cows (?!) rules to check where errors are reported.
                        </em>
                    </dd>
                </dl>
            </div>
        </div>
    </div>
</div>

<h3 id="generic-services-section">The GenericService methods</h3>
<p>
    In the Controller the
    <code>ListService</code>
    (<a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/ListService.cs" target="_blank">code</a>),
    <code>DetailService</code>
    (<a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/DetailService.cs" target="_blank">code</a>),
    <code>UpdateService</code>
    (<a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/UpdateService.cs" target="_blank">code</a>),
    <code>CreateService</code>
    (<a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/CreateService.cs" target="_blank">code</a>) and
    <code>DeleteService</code>
    (<a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/DeleteService.cs" target="_blank">code</a>)
    are called. Click on the panel below to get more details about how these work.
</p>
<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a data-toggle="collapse" href="#GenericService">
                GenericService methods
            </a>
        </h4>
        <div id="GenericService" class="panel-collapse collapse">
            <div class="panel-body">
                <dl>
                    <dt>
                        Basic, one stage services, i.e.
                        <a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/ListService.cs" target="_blank">ListService</a>
                        and <a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/DetailService.cs" target="_blank">DetailService</a>

                    </dt>
                    <dd>
                        <p>
                            These services have only one stage, i.e. the production of data. Therefore they are nice and simple.
                        </p>
                    </dd>
                    <dt id="GenericService-two-stage">
                        The <a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/CreateService.cs" target="_blank">CreateService</a>
                        and the <a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/UpdateService.cs" target="_blank">UpdateService</a>
                        need two stages.
                    </dt>
                    <dd>
                        <p>These services have a setup stage to provide the initial data to display to the user. Therefore there is:</p>
                        <ul>
                            <li>
                                A <a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/CreateSetupService.cs" target="_blank">CreateSetupService</a>
                                which has a <code>GetDto&lt;T&gt;()</code> method, where T is either a class that is used in EF or
                                a DTO that has inherited from EfGenericDto or EfGenericDtoAsync.
                            </li>
                            <li>
                                A <a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/UpdateSetupService.cs" target="_blank">UpdateSetupService</a>
                                which has a <code>GetOriginal(param object[] keys)</code> method, where you have to
                                supply the primary key, or if multiple keys then they must be in the order that LINQ expects.
                            </li>
                        </ul>
                    </dd>
                    <dt>
                        The
                        <a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Services/Concrete/ListService.cs" target="_blank">ListService</a>
                        returns IQueryable
                    </dt>
                    <dd>
                        This is really important, as the actual SQL command has not been created yet. This means you can use LINQ
                        command like <code>.Take(n)</code> or <code>.Skip(m)</code> to do paging, or apply further filters etc.
                        and they will become part of the SQL request. That is really important for producing efficient database access commands.
                    </dd>
                </dl>
            </div>
        </div>
    </div>
</div>

<h3>The DetailPostDto <abbr title="Data Transfer Object">DTO</abbr></h3>
<p>
    The <code>DetailPostDto</code>
    (<a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/ServiceLayer/PostServices/DetailPostDto.cs" target="_blank">code</a>)
    is at the heart of how the Create and Edit actions allows the user to setup or change a Post's author or tags. It inherits the abstract class <code>EfGenericDto</code>
    (<a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Core/EfGenericDto.cs" target="_blank">code</a>) and overrides a few
    methods to handle the Post's <code>BlogId</code> and <code>Tag</code> Collection.
</p>
<p>
    Click on the panel below to get more details about how these work.
</p>
<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a data-toggle="collapse" href="#DetailPostDto">
                DetailPostDto <abbr title="Data Transfer Object">DTO</abbr> Actions
            </a>
        </h4>
        <div id="DetailPostDto" class="panel-collapse collapse">
            <div class="panel-body">
                <dl>
                    <dt>Adding UI controls for changing a Post's author and tags</dt>
                    <dd>
                        <p>
                            The <code>DetailPostDto</code> adds two lists; a
                            <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/ServiceLayer/UiClasses/DropDownListType.cs" target="_blank">DropDownListType</a>
                            called <code>Bloggers</code> and a
                            <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/ServiceLayer/UiClasses/MultiSelectListType.cs" target="_blank">MultiSelectListType</a>
                            called <code>UserChosenTags</code>. These two provide the data in a form that the MVC view can use.
                        </p>
                        <p>
                            The MVC Views, such as
                            <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/SampleWebApp/Views/Posts/Edit.cshtml" target="_blank">Edit</a>
                            then uses two EditorTemplates of the same name, i.e.
                            <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/SampleWebApp/Views/Shared/EditorTemplates/DropDownListType.cshtml" target="_blank">DropDownListType</a>
                            and
                            <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/SampleWebApp/Views/Shared/EditorTemplates/MultiSelectListType.cshtml" target="_blank">MultiSelectListType</a>.
                            The names tell you what they do.
                        </p>
                    </dd>
                </dl>
                <dl>
                    <dt>Filling in the UI lists prior to display</dt>
                    <dd>
                        <p>
                            The <code>DetailPostDto</code> inherits from the <code>EfGenericDto</code>
                            (<a href="https://github.com/JonPSmith/GenericServices/blob/master/GenericServices/Core/EfGenericDto.cs" target="_blank">code</a>)
                            and overrides the <code>SetupSecondaryData</code> method. This method makes sure that the two lists are filled with the correct data
                            prior to MVC displaying the Create or Edit View.
                        </p>
                    </dd>
                    <dt>Updating the Author (BlogId) and Tags</dt>
                    <dd>
                        <p>
                            As well as overriding the <code>SetupSecondaryData</code> method in the <code>EfGenericDto</code>
                            <code>CopyDtoToData</code> also overrides the <code>CopyDtoToData</code> method.
                            This method is called every time the <code>DetailPostDto</code>
                            properties are copied back to the <code>Post</code> class.
                        </p>
                        <p>
                            The <code>DetailPostDto</code> also overrides the <code>CopyDtoToData</code> method. In this new method it has code to
                            obtain the user's choices from the Bloggers and UserChosenTags lists and then updates the
                            properties <code>BlogId</code> and <code>Tags</code>. It then calls the base <code>CopyDtoToData</code> to copy the updated
                            properties back into the <code>Post</code> class prior to <abbr title="Entity Framework">EF</abbr>'s SubmitChanges method being called.
                        </p>
                    </dd>
                    <dt>Other interesting stuff</dt>
                    <dd>
                        <ul>
                            <li>
                                The property <code>SupportedFunctions</code> has to be overrriden and says what services the DTO can support.
                                See the different setting in
                                <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/ServiceLayer/PostServices/DetailPostDto.cs" target="_blank">DetailPostDto</a>
                                and
                                <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/ServiceLayer/PostServices/SimplePostDto.cs" target="_blank">DetailPostDto</a>
                            </li>
                            <li>
                                When doing a Create or Edit(Update) the <code>CopyDtoToData</code> is called.
                                Only properties that have a public setter, e.g. <code>public int BlogId { get; set; }</code>
                                are copied to the data. This means you can exclude items that either
                                you don't want to change or <abbr title="Entity Framework">EF</abbr> is responsible for setting.
                                (see <code>LastUpdated</code> property in <code>Post</code> class which is filled in by <abbr title="Entity Framework">EF</abbr>.)
                            </li>
                            <li>
                                I would have liked all the references to the data classes and the DTO to be via interfaces
                                as I think this gives better separation of classes, e.g.
                                <code>IxxxService&lt;IPost, IDetailedPostDto&gt;</code> instead of
                                <code>IxxxService&lt;Post, DetailedPostDto&gt;</code>.
                                I did try to get Interfaces to work but <abbr title="Entity Framework">EF</abbr> does not support Interfaces, and using a interface for the DTOs had a few problems too.
                                Nice aim to use interfaces, but I think the classes are simple enough to use direct.
                                (Note: when it comes to running business level actions I do use interfaces for obviosu reasons.)
                            </li>
                        </ul>
                    </dd>
                </dl>
            </div>
        </div>
    </div>
</div>

<h3 id="di-section">How <abbr title="Dependency Injection">DI</abbr> is used in SampleMvcWebApp</h3>
<p>
    Using <abbr title="Dependency Injection">DI</abbr> to inject Action parameters (see
    <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/SampleWebApp/Infrastructure/DiModelBinder.cs" target="_blank">MVC module that does this</a>)
    in a Controller is a short and efficient way of injecting specific services to each action.
    Also by using Generic DI binding
    (see <a href="https://github.com/autofac/Autofac/wiki/Open-Generics">example from AutoFac</a>) means that the DI can define all the
    possible service options quickly in its registration file
    (see <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/ServiceLayer/Startup/ServiceLayerModule.cs" target="_blank">in SampleMvcWebApp</a>)
</p>
<p>
    Click on the panel below to get more details about how these work.
</p>
<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a data-toggle="collapse" href="#DIused">
                How DI is used in SampleMcvWebpp
            </a>
        </h4>
        <div id="DIused" class="panel-collapse collapse">
            <div class="panel-body">
                <dl>
                    <dt>How we inject the action Parameter</dt>
                    <dd>
                        <p>
                            Many years ago I came across an
                            <a href="http://alexmg.com/introducing-action-injection-with-autofac-aspnet-mvc-integration/" target="_blank">interesting blog post</a>
                            by by Alex Meyer-Gleaves who is one of the main people involved in AutoFac.
                            In Alex's post he was proposing injecting method via each Action method in a controller rather
                            than the more normal constructor injection.
                        </p>
                        <p>
                            I thought that was a great idea which solved so many problems so I implemented it, but in a different way to Alex's post.
                            I create a new MVC
                            <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/SampleWebApp/Infrastructure/DiModelBinder.cs" target="_blank">Model Binder</a>
                            which is assigned in the Default Model Binder in the
                            <a href="https://github.com/JonPSmith/SampleMvcWebApp/blob/master/SampleWebApp/Global.asax.cs" target="_blank">Global.asax.cs</a>
                            using the command <code>ModelBinders.Binders.DefaultBinder = new DiModelBinder();</code>
                        </p>
                    </dd>
                    <dt>... however you can use GenericServices without DI</dt>
                    <dd>
                        <p>
                            While we talk a lot about DI the GenericServices framework does NOT rely on DI at all.
                            It just makes creating these services much easier and clearer.
                            So, if you can't use DI then GenericServices may still be useful to you.
                        </p>
                    </dd>
                </dl>
            </div>
        </div>
    </div>
</div>

